<!--听书分类页入口配置-->
<template>
  <el-dialog
    title="分类页入口配置"
    style="min-width: 1500px;"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
             label-width="80px">
      <el-form-item label="配置名称" prop="name">
        <el-input v-model="dataForm.name" placeholder="请输入分类页入口配置名称（如：春节用）" style="width: 300px;" clearable></el-input>
      </el-form-item>
      <div v-for="(item,index) in itemList" :key="index" class="item-wrapper"
           v-dragging="{ item: item, list: itemList, group: 'item' }">
        <span style="color: #f56c6c;margin-right: 4px">*</span>
        <span class="label">入口 {{index+1}}：</span>
        <div class="move-tip-icon">&lt;&gt;</div>
        <el-input v-model="item.title" placeholder="请输入名称" style="width: 200px;" clearable
                  class="item-span"></el-input>
        <el-select v-model="item.categoryIndex" class="item-span" placeholder="请选择音频分类">
          <el-option
            v-for="(option,index) in selectOptions"
            :key="option.id"
            :label="option.name"
            :value="index">
          </el-option>
        </el-select>
        <el-upload
          style="display: inline-block"
          class="item-span"
          :action="uploadIconUrl"
          :show-file-list="false"
          :on-success="handleIconSuccess"
          :before-upload="beforeIconUpload"
          :on-error="handleIconError">
          <img v-if="item.pic" :src="item.pic" class="uploader-icon" @click="getUploadTag(item,index)">
          <div v-else class="uploader-icon" @click="getUploadTag(item,index)">请上传icon</div>
        </el-upload>
        <el-upload
          style="display: inline-block"
          class="item-span"
          :action="uploadIconUrl"
          :show-file-list="false"
          :on-success="handleBackImgSuccess"
          :before-upload="beforeBackImgUpload"
          :on-error="handleBackImgError">
          <img v-if="item.backImg" :src="item.backImg" class="uploader-backImg" @click="getUploadTag(item,index)">
          <div v-else class="uploader-backImg" @click="getUploadTag(item,index)">请上传封面图</div>
        </el-upload>
        <el-button type="danger" icon="el-icon-delete" circle @click="deleteItem(index)"></el-button>
        <!--</div>-->
      </div>
      <el-form-item>
        <el-button type="primary" @click="addList">新增一项</el-button>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
    <div style="margin-left: 80px;color:#f56c6c;" v-if="showErrorTip">
      <i class="el-icon-warning" style="color: red;margin-right: 10px;"></i>还有信息未填完整，请检查！
    </div>
  </el-dialog>
</template>

<script>
  export default {
    data () {
      return {
        visible: false,
        showErrorTip: false,
        uploadIconUrl: this.$http.adornUrl(`/sys/oss/upload?token=${this.$cookie.get('token')}`),
        itemList: [],
        uploadItem: {},
        uploadItemIndex: 0,
        selectOptions: [],
        dataForm: {
          id: '',
          name: '',
        },
        dataRule: {
          name: [
            {required: true, message: '名称不能为空', trigger: 'blur'}
          ]
        }
      }
    },
    methods: {
      init (id) {
        let _this = this
        _this.showErrorTip = false
        _this.itemList = [{
          title: '', pic: '', categoryIndex: '', backImg: ''
        }]
        _this.selectOptions = []
        _this.dataForm.id = id || 0
        _this.visible = true
        _this.$nextTick(() => {
          _this.$refs['dataForm'].resetFields()
          _this.getCategoryList()
          if (_this.dataForm.id) {
            _this.$http({
              url: _this.$http.adornUrl(`/picbook/appconf/v2/info/media/${_this.dataForm.id}`),
              method: 'post',
              params: _this.$http.adornParams({id: _this.dataForm.id})
            }).then(({data}) => {
              if (data && data.code === 0) {
                _this.dataForm.name = data.data.appConf.name
                _this.itemList = []
                data.data.categoryConfs.forEach(function (item) {
                  var categoryIndex = ''
                  _this.selectOptions.map(function (value, index) {
                    if (value.id == item.categoryId) {
                      categoryIndex = index
                      return
                    }
                  })
                  _this.itemList.push({
                    title: item.title,
                    pic: item.pic,
                    categoryIndex: categoryIndex,
                    backImg: item.backImg,
                  })
                })
              }
            })
          }
        })
      },
      // 表单提交
      dataFormSubmit () {
        let _this = this
        _this.showErrorTip = false
        this.itemList.map(function (value, index, array) {
          if (!_this.selectOptions || value.categoryIndex === '' || !_this.selectOptions[value.categoryIndex].id || !value.title || !value.pic || !value.backImg) {
            _this.showErrorTip = true
            return
          }
        })
        this.$refs['dataForm'].validate((valid) => {
          if (valid && !_this.showErrorTip) {
            var categoryConfs = []
            _this.itemList.map(function (value, index, array) {
              var categoryConf = {
                title: value.title,
                pic: value.pic,
                backImg: value.backImg,
                type: _this.selectOptions[value.categoryIndex].type,
                categoryId: _this.selectOptions[value.categoryIndex].id
              }
              categoryConfs.push(categoryConf)
            })
            var appConf = {name: this.dataForm.name}
            this.dataForm.id && (appConf.id = this.dataForm.id)
            let url = _this.dataForm.id ? '/picbook/appconf/v2/update' : '/picbook/appconf/v2/save/audio/category'
            this.$http({
              url: this.$http.adornUrl(url),
              method: 'post',
              data: this.$http.adornData({
                appConf: appConf,
                categoryConfs: categoryConfs
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      addList () {
        this.itemList.push({title: '', pic: '', categoryId: '', backImg: ''})
      },
      deleteItem (index) {
        if (this.itemList.length > index && this.itemList.length > 1) {
          this.itemList.splice(index, 1)
        } else if (index == 0 && this.itemList.length == 1) {
          this.itemList = [{title: '', pic: '', categoryIndex: '', backImg: ''}]
        }
      },
      handleIconSuccess (res, file) {
        this.uploadItem.pic = res.url
      },
      beforeIconUpload (file) {
        if (file.type.indexOf('image') < 0) {
          this.$message.error('图片格式不正确')
          return false
        }
      },
      handleIconError (err, file, fileList) {
        this.$message.error('上传失败')
      },
      handleBackImgSuccess (res, file) {
        this.uploadItem.backImg = res.url
      },
      beforeBackImgUpload (file) {
        if (file.type.indexOf('image') < 0) {
          this.$message.error('图片格式不正确')
          return false
        }
      },
      handleBackImgError (err, file, fileList) {
        this.$message.error('上传失败')
      },
      getUploadTag (item, index) {
        this.uploadItem = item
        this.uploadItemIndex = index
      },
      //获取下拉框列表集合
      getCategoryList () {
        this.$http({
          url: this.$http.adornUrl(`/picbook/combobox/audio/listCategoryColumn`),
          method: 'post',
          data: this.$http.adornData()
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.selectOptions = data.data
          }
        })
      }
    }
  }
</script>
<style lang="less" scoped>
  .uploader-icon {
    border: 1px solid #d9d9d9;
    border-radius: 50%;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 80px;
    height: 80px;
    line-height: 80px;
    font-size: 10px;
  }

  .uploader-backImg {
    border: 1px solid #d9d9d9;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 120px;
    height: 80px;
    line-height: 80px;
    font-size: 10px;
  }

  .item-wrapper {
    display: flex;
    align-items: center;
    .label {
      width: 68px;
    }
    .item-span {
      margin-right: 12px;
    }
  }

  .move-tip-icon {
    display: inline-block;
    font-size: 18px;
    font-weight: 400;
    transform: rotate(90deg);
    -ms-transform: rotate(90deg); /* IE 9 */
    -moz-transform: rotate(90deg); /* Firefox */
    -webkit-transform: rotate(90deg); /* Safari 和 Chrome */
    -o-transform: rotate(90deg); /* Opera */
  }
</style>
